package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.NumberUtils;
import com.leyou.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;


@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private String KEY_PREFIX="user:code:phone:";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

   /* public Boolean checkUserData(String data, Integer type) {
        User u = new User();
        switch (type) {
            case 1:
                u.setUsername(data);
                break;
            case 2:
                u.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INNER_SERVICE_ERROR);
        }
        int count = this.userMapper.selectCount(u);


        return count==0;
    }
*/




    public Boolean checkUserData(String data, Integer type) {

        User record=new User();
        if (1==type){
            try {
                record.setUsername(data);
            } catch (Exception e) {
                throw new LyException(ExceptionEnum.INNER_SERVICE_ERROR);
            }
        }else if (2==type){
            try {
                record.setPhone(data);
            } catch (Exception e) {
                throw new LyException(ExceptionEnum.INNER_SERVICE_ERROR);
            }
        }else {
            throw new LyException(ExceptionEnum.INVALID_PARAM);
        }

        int count = userMapper.selectCount(record);

        return count==0;
    }


    public void sendCode(String phone) {

        String code = NumberUtils.generateCode(6);
        Map<String,String> msg=new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);

        try {
            this.amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);
        } catch (AmqpException e) {
            throw new LyException(ExceptionEnum.INNER_SERVICE_ERROR);
        }

        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,10, TimeUnit.MINUTES);



    }


    public void register(User user, String code) {

        String cachCode = (String) redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        if (!StringUtils.equals(code,cachCode)){

            throw new LyException(ExceptionEnum.CODE_ERROR);
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));

            int count = userMapper.insertSelective(user);

        if (count!=1) {
            throw new LyException(ExceptionEnum.INNER_SERVICE_ERROR);
        }


    }

    public UserDTO queryUserByUsernameAndPassword(String username, String password) {

        User record=new User();
        record.setUsername(username);
        User user = userMapper.selectOne(record);
        if (null==user){
            throw new LyException(ExceptionEnum.USER_NAME_NOT_FOUND);
        }
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(ExceptionEnum.USER_NAME_OR_PASSWORD_ERROR);
        }

        return BeanHelper.copyProperties(user,UserDTO.class);
    }
}
